from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from rest_framework import generics

from rest_framework.views import APIView

from apps.member.models import MemberRecord
from apps.member.serializers import MemberMobileSignSerializer, CollectSerizlizer, BrowseSerizlizer
from apps.system.models import VCode
from utils import response_ok, response_error
from utils.permissions import IsMemberUser
# Create your views here.
from utils.exception import CustomError


class MemberLoginView(APIView):
    # 验证码注册登录
    serializer_class = MemberMobileSignSerializer

    def post(self, request, *args, **kwargs):
        """验证码注册登录"""
        with transaction.atomic():
            ser = self.serializer_class(data=request.data)
            if ser.is_valid():
                return response_ok(ser.validated_data)
            return response_error('手机号或者验证码错误！')


class MemberSendVcodeView(APIView):
    # 获取验证码

    def get(self, request, *args, **kwargs):
        mobile = request.GET.get('mobile')
        # type = int(request.GET.get('type'))
        try:
            with transaction.atomic():
                message = VCode.send(mobile, VCode.SIGN)
        except CustomError as e:
            return response_error(e.get_error_msg())

        return response_ok(message)


class MemberResetPasswordView(APIView):
    # 重置密码
    permission_classes = [IsMemberUser]

    def post(self, request):
        data = request.data
        user = request.user
        if not data['vcode']:
            raise CustomError('请输入验证码！')
        if not data['password']:
            raise CustomError('请输入密码！')
        # 验证验证码
        VCode.verify(user.username, data['vcode'], VCode.SIGN)
        with transaction.atomic():
            user.set_password(data['password'])
            user.save()
            MemberRecord.objects.create(content_object=user, user=user, operate=MemberRecord.SET_PASSWORD,
                                        describe='修改密码')
        return response_ok()


class MemberlikeViewSet(APIView):
    '''点赞'''
    permission_classes = (IsMemberUser,)

    def get(self, request):
        object_id = request.GET.get('object_id')
        model_name = request.GET.get('model_name')
        if not model_name and object_id:
            return response_ok('参数错误。')

        # (ContentType表对象有model_class) 方法，取到对应model
        content_type = ContentType.objects.get(model=model_name.lower())
        model = content_type.model_class()

        instance = model.objects.filter(pk=object_id).first()

        if not instance:
            return response_error('为找到对应的media')

        with transaction.atomic():

            member_record = MemberRecord.objects.filter(content_type=content_type, object_id=object_id,
                                                        user=self.request.user, operate=MemberRecord.LIKE).first()
            if member_record:
                # 存在，删除
                instance.like_count -= 1
                instance.save()
                member_record.delete()
                return response_ok('取消点赞')
            # 不存在，创建
            instance.like_count += 1
            instance.save()
            MemberRecord.objects.create(content_object=instance, user=self.request.user, operate=MemberRecord.LIKE,
                                        describe='点赞')
        return response_ok('点赞成功')


class MemberCollectViewSet(APIView):
    '''收藏'''
    permission_classes = (IsMemberUser,)

    def get(self, request):
        object_id = request.GET.get('object_id')
        model_name = request.GET.get('model_name')
        if not model_name and object_id:
            return response_ok('参数错误。')

        # (ContentType表对象有model_class) 方法，取到对应model
        content_type = ContentType.objects.get(model=model_name.lower())
        model = content_type.model_class()

        instance = model.objects.filter(pk=object_id).first()

        if not instance:
            return response_error('为找到对应的实体')

        with transaction.atomic():

            member_record = MemberRecord.objects.filter(content_type=content_type, object_id=object_id,
                                                        user=self.request.user, operate=MemberRecord.COLLECT).first()
            if member_record:
                # 存在，删除
                instance.like_count -= 1
                instance.save()
                member_record.delete()
                return response_ok('取消收藏')
            # 不存在，创建
            instance.like_count += 1
            instance.save()
            MemberRecord.objects.create(content_object=instance, user=self.request.user, operate=MemberRecord.COLLECT,
                                        describe='收藏')
        return response_ok('收藏成功')


class MemberCollectionViewSet(generics.ListAPIView):
    '''我的收藏'''
    queryset = MemberRecord.objects.filter(operate=MemberRecord.COLLECT)
    serializer_class = CollectSerizlizer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(user=self.request.user)
        return queryset


class MemberBrowseViewSet(generics.ListAPIView):
    '''我的浏览记录'''
    queryset = MemberRecord.objects.filter(operate=MemberRecord.BROWSE)
    serializer_class = BrowseSerizlizer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(user=self.request.user)
        return queryset


class TimeLineViewSet(generics.ListAPIView):
    # queryset =
    pass
